package tom.spring.cloud.gateway.zuul.version;

import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 映射路径配置，可以用来对接口进行分版本号控制
 * 如对serviceId为 a-v1的 映射为v1/a
 *                 a-v2的 映射为v2/a
 *                 以达到接口分版本兼容的目的
 *
 * 访问：http://localhost:8060/actuator/mappings
 *      http://localhost:8060/actuator/routes
 *      查看映射信息
 *
 *  访问：http://localhost:8060/01/provider/api/hello?token=a 即可访问到provider01的接口
 *      http://localhost:8060/02/consumer/feign/api/hello?token=aa 等于 http://localhost:8060/consumer02/feign/api/hello?token=aa
 * @author ZHUFEIFEI
 */
@Configuration
public class PatternRouterMapperConfig {

    @Bean
    public PatternServiceRouteMapper versionPattern() {
        //consumer01映射为 01/consumer
        return new PatternServiceRouteMapper("(?<name>[a-zA-Z]+)(?<version>\\d+$)"
                , "${version}/${name}");
    }

    public static void main(String[] args) {
        String pat = "${version}/${name}";
        String pattern = "(?<name>[a-zA-Z]+)(?<version>\\d+$)";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher("consumer01");
        while(m.find()) {
            System.out.println(m.group("name"));
            System.out.println(m.group("version"));
        }
        System.out.println(m.replaceFirst(pat));
    }

}
